<template>
  <div>
    <!-- 搜索添加栏 -->
    <Row>
      <Card>
        <Form ref="search" :model="searchData" :rules="searchReg" :label-width="80">
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="部门">
                <Input
                  v-model="searchData.department"
                  suffix="ios-search"
                  placeholder="请输入用户名称"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="部门简称">
                <Input
                  v-model="searchData.departAddr"
                  suffix="ios-search"
                  placeholder="请输入部门简称"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="部门类型">
                <Select clearable v-model="searchData.departType" placeholder="请输入部门类型">
                  <Option value="乡镇">乡镇</Option>
                  <Option value="县直单位">县直单位</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="单位分类">
                <!-- <Input
                  v-model="searchData.departClas"
                  suffix="ios-search"
                  placeholder="请输入单位分类"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>-->
                <Select
                  clearable
                  v-model="searchData.departClas"
                  style="width: auto"
                  placeholder="请选择单位分类"
                >
                  <Option
                    v-for="item in departclssArr"
                    :value="item.id"
                    :key="item.classname"
                  >{{ item.classname }}</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="部门旧名称">
                <Input
                  v-model="searchData.departOldName"
                  suffix="ios-search"
                  placeholder="请输入部门旧名称"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="部门旧简称">
                <Input
                  v-model="searchData.departOldAddr"
                  suffix="ios-search"
                  placeholder="请输入部门旧简称"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
          </Row>
          <FormItem>
            <Button
              v-if="btnAccess.query"
              type="primary"
              style="marigin:0 20px"
              :loading="searchLoading"
              @click="searchSubmit(10,1)"
            >提交搜索</Button>
            <Button @click="submitReset">重置搜索</Button>
          </FormItem>
        </Form>
      </Card>
    </Row>

    <!-- 表格 -->
    <Row style="margin-top:20px">
      <Card>
        <div class="btn-arrs">
          <Button type="info" v-if="btnAccess.add" @click="showUserModal">添加部门单位</Button>
          <Button
            v-if="btnAccess.upd"
            type="primary"
            @click="showEditClass"
            :disabled="isSelectEdit"
            style="margin-left:10px;margin-bottom:10px;"
          >批量编辑单位分类</Button>
        </div>
        <Table
          @on-selection-change="selectChange"
          :loading="tabelLoading"
          :columns="userHead"
          :data="userData"
          border
        ></Table>
        <!-- <div style="margin-top:20px;margin-left:35%">
          <Page
            @on-change="pageNumberChange"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>-->
      </Card>
    </Row>
    <!-- 添加/编辑 -->
    <Modal
      v-model="isUserModal"
      :title="userModalTitle"
      :loading="userModalLoading"
      @on-cancel="cancelUserModal"
    >
      <Form ref="userManagement" :model="userForm" :rules="userReg" :label-width="80">
        <FormItem label="部门" prop="department">
          <Input v-model="userForm.department" placeholder="请输入部门" style="width: 300px"></Input>
        </FormItem>
        <FormItem label="部门简称" prop="departAddr">
          <Input v-model="userForm.departAddr" placeholder="请输入部门简称" style="width: 300px"></Input>
        </FormItem>

        <FormItem label="部门类型" prop="departType">
          <Select v-model="userForm.departType" placeholder="请输入部门类型" style="width: 300px">
            <Option value="乡镇">乡镇</Option>
            <Option value="县直单位">县直单位</Option>
          </Select>
        </FormItem>

        <FormItem label="单位分类" prop="departClas">
          <Select v-model="userForm.departClas" style="width:300px" placeholder="请选择单位分类">
            <Option
              v-for="item in departclssArr"
              :value="item.id"
              :key="item.classname"
            >{{ item.classname }}</Option>
          </Select>
        </FormItem>

        <FormItem label="部门旧名称" prop="departOldName">
          <Input v-model="userForm.departOldName" placeholder="请输入部门旧名称" style="width: 300px"></Input>
        </FormItem>

        <FormItem label="部门旧简称" prop="departOldAddr">
          <Input v-model="userForm.departOldAddr" placeholder="请输入部门旧简称" style="width: 300px"></Input>
        </FormItem>

        <FormItem label="备注" prop="remark">
          <Input
            v-model="userForm.remark"
            placeholder="请输入备注"
            style="width: 300px"
            type="textarea"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          v-if="btnAccess.upd"
          type="primary"
          size="large"
          :loading="userModalLoading"
          @click="submitUserModal"
        >提交</Button>
        <Button size="large" @click="cancelUserModal">取消</Button>
      </div>
    </Modal>

    <!-- 批量选择单位分类 -->
    <Modal v-model="classModal" title="批量选择单位分类" @on-ok="submitClass" @on-cancel="cancelClassModal">
      <Form :model="userForm">
        <FormItem label="单位分类">
          <Select v-model="userForm.departClas" style="width:300px" placeholder="请选择单位分类">
            <Option
              v-for="item in departclssArr"
              :value="item.id"
              :key="item.classname"
            >{{ item.classname }}</Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import { hasOneOf } from "@/libs/tools";
import { userAjax } from "@/api/systemMange";
// 删除URL
const DELETE_URL = "/department/delete";
// 修改URL
const UPDATE_URL = "/department/update";
// 添加URL
const INSERT_URL = "/department/insert";
// 查询URL
const QUERY_URL = "/department/query";
// 批量修改单位分类
const BULKCHANGE_URL = "/department/batchUpdateClass";
const INSERT_TITLE = "添加";
const UPDATE_TITLE = "编辑";
export default {
  data() {
    // 验证手机号码
    return {
      // 增删改查权限按钮
      btnAccess: {
        add: true,
        add2: "inline-block",
        del: "inline-block",
        upd: true,
        query: true
      },
      // roleSelect: false, // 权限管理
      classModal: false, // 修改单位分类模态框
      isUserModal: false, // 模态框
      searchLoading: false, // 搜索Loading
      userModalLoading: false, // 提交loading
      tabelLoading: false, // 表格loading
      userModalTitle: "", // 模态框title
      isResponsible: "",
      pageSize: 10,
      pageNumber: 1,
      pageTotal: 10,
      currentPage: 1, // 记录当前页数
      departclssArr: [],
      userForm: {
        department: "", // 用户名
        departAddr: "", // 部门简称
        departType: "", // 部门类型
        departClas: "", // 单位分类
        departOldName: "", // 部门旧名称
        departOldAddr: "", // 部门旧简称
        remark: "" // 备注
      },
      searchData: {
        department: "", // 部门
        departAddr: "", // 部门简称
        departType: "", // 部门类型
        departClas: "", // 单位分类
        departOldName: "", // 部门旧名称
        departOldAddr: "", // 部门旧简称
        remark: "" // 备注
      },
      userData: [], // 表格数据
      searchReg: {},
      userReg: {
        department: [
          {
            required: true,
            message: "请输入部门",
            trigger: "blur"
          }
        ],
        departAddr: [
          {
            required: true,
            message: "请输入部门简称",
            trigger: "blur"
          }
        ],
        departType: [
          {
            required: true,
            message: "请输入部门类型",
            trigger: "change"
          }
        ]
      },
      userHead: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "序号",
          type: "index",
          width: 60,
          align: "center"
        },
        {
          title: "部门",
          key: "department"
        },
        {
          title: "部门简称",
          key: "departAddr"
        },
        {
          title: "部门类型",
          key: "departType"
        },
        {
          title: "单位分类",
          key: "departClas",
          render: (h, params) => {
            // id转换中文显示
            let text = "";
            let arr = this.departclssArr;
            let val = params.row.departClas;
            for (let i = 0; i < arr.length; i++) {
              if (val === arr[i].id + "") {
                text = arr[i].classname;
              }
            }
            return h("div", text);
          }
        },
        {
          title: "部门旧名称",
          key: "departOldName"
        },
        {
          title: "部门旧简称",
          key: "departOldAddr"
        },
        {
          title: "备注",
          key: "remark"
        },
        {
          title: "操作",
          key: "action",
          width: 220,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.userForm = JSON.parse(JSON.stringify(params.row)); // 深拷贝
                      this.userModalTitle = "编辑";
                      this.isUserModal = true;
                    }
                  }
                },
                "查看或编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error"
                  },
                  style: {
                    display: this.btnAccess.del
                  },
                  on: {
                    click: () => {
                      this.deleteUser(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      isSelectEdit: true // 是否选中批量修改
    };
  },
  methods: {
    // 搜索
    searchSubmit(pageSize, pageNumber) {
      this.searchLoading = true;
      this._getUserData(this.searchData, QUERY_URL, pageSize, pageNumber);
    },
    // 重置搜索
    submitReset() {
      this.searchLoading = false;
      this.searchData = {
        department: ""
      };
    },
    // 删除用户
    deleteUser(row) {
      if (this.accessAgent) {
        this.$Message.error("权限不足！");
        return;
      }
      this.$Modal.confirm({
        title: "删除用户",
        content: "<p>删除完成后将无法恢复</p>",
        loading: true,
        onOk: () => {
          this._userAjax(row, DELETE_URL).then(result => {
            this.$Modal.remove();
            if (result.code === "200") {
              this.$Message.info("删除成功!");
              this._getUserData(
                this.userData,
                QUERY_URL,
                this.pageSize,
                this.currentPage
              );
            } else {
              this.$Message.error("删除失败！");
            }
          });
        }
      });
    },
    // 显示模态框
    showUserModal() {
      this.userModalTitle = "添加";
      this.isUserModal = true;
    },
    // 提交
    submitUserModal() {
      this.$refs["userManagement"].validate(valid => {
        if (valid) {
          this.userModalLoading = true;
          if (this.userModalTitle === INSERT_TITLE) {
            this._userAjax(this.userForm, INSERT_URL).then(result => {
              this.isUserModal = false;
              this.userModalLoading = false;
              if (result.code === "200") {
                this.$Message.success("添加成功！");
                this._getUserData(
                  this.searchData,
                  QUERY_URL,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error(result.message);
              }
            });
          } else if (this.userModalTitle === UPDATE_TITLE) {
            this._userAjax(this.userForm, UPDATE_URL).then(result => {
              this.isUserModal = false;
              this.userModalLoading = false;
              if (result.code === "200") {
                this.$Message.success("添加成功！");
                this._getUserData(
                  this.searchData,
                  QUERY_URL,
                  this.pageSize,
                  this.currentPage
                );
              } else {
                this.$Message.error("添加失败！");
              }
            });
          }
        } else {
          this.$Message.error("请填写完整！");
        }
      });
    },
    cancelUserModal() {
      this.$refs["userManagement"].resetFields();
      this.userModalLoading = false;
      this.isUserModal = false;
      this.userForm = {
        department: "" // 用户部门
      };
    },
    // 页码
    pageNumberChange(pageNumber) {
      this.currentPage = pageNumber;
      this.pageNumber = pageNumber;
      this._getUserData(
        this.searchData,
        QUERY_URL,
        this.pageSize,
        this.pageNumber
      );
    },
    // 页数
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getUserData(
        this.searchData,
        QUERY_URL,
        this.pageSize,
        this.pageNumber
      );
    },
    // 添加/修改
    _userAjax(formData, url) {
      const keyOne = "departmentEntity";
      return new Promise((resolve, reject) => {
        userAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 查询
    _getUserData(formData, url, pageSize, pageNumber) {
      this.tabelLoading = true;
      formData = Object.assign(formData, {
        pageSize,
        pageNumber
      });
      const keyOne = "departmentFilter";
      userAjax({ formData, url, keyOne })
        .then(result => {
          this.tabelLoading = false;
          if (result.data.code === "200") {
            this.$store.state.user.departmentList = result.data.results.list; // 重新赋值最新部门
            this.searchLoading = false;
            this.userData = result.data.results.list;
            this.pageTotal = result.data.results.pageTotal;
            this.departclssArr = result.data.results.departclssList; // 单位分类赋值
            this.$Message.success("查询成功");
          } else {
            this.$Message.error("查询失败");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 批量修改分类
    selectChange(selection) {
      let arr = []; // 用户id
      selection.forEach(item => {
        arr.push(item.id);
      });

      if (arr.length === 0) {
        this.isSelectEdit = true;
      } else {
        this.isSelectEdit = false;
      }
      this.userForm.listId = arr; // 选中的id
    },
    // 提交批量修改
    submitClass() {
      console.log(this.userForm.listId);
      this._userAjax(this.userForm, BULKCHANGE_URL).then(result => {
        if (result.code === "200") {
          this.$Message.success(result.message);
          this._getUserData(
            this.searchData,
            QUERY_URL,
            this.pageSize,
            this.currentPage
          );
        } else {
          this.$Message.error(result.message);
        }
      });
      this.classModal = false;
    },
    cancelClassModal() {
      this.classModal = false;
    },
    // 显示批量修改模态框
    showEditClass() {
      this.classModal = true;
    }
  },
  mounted() {},
  created() {
    this._getUserData(
      this.searchData,
      QUERY_URL,
      this.pageSize,
      this.pageNumber
    );
    // 获取按钮权限
    let btnAccess = sessionStorage.getItem("btnaccess");
    this.globalFunction(btnAccess);
  },
  computed: {
    getDepartmentList() {
      return this.$store.state.user.departmentList;
    },
    getDepartment() {
      return this.$store.state.user.department;
    },
    access() {
      return this.$store.state.user.access;
    },
    // 管理员
    accessAdmin() {
      return hasOneOf(["admin"], this.access);
    },
    // 责任人
    accessRespons() {
      return hasOneOf(["responsible"], this.access);
    },
    // 经办人
    accessAgent() {
      return hasOneOf(["agent"], this.access);
    }
    //
  }
};
</script>
<style scoped>
</style>
